//详细地址
var locationDetailInfoDialog;
var queryLocation;
//统计页面跳转查询详情
var gotoSearchFaultDetails;
//统计页面传递过来的参数
var passParams;
//首页跳转
var itemSearch;
var realTimeFailWarn;
var searchFaultDetail;
//跳转到车辆画像-车辆信息
var goCarInfo;
//车队长跳转
var captainSearch;
//跳转到线路信息页面
var goLineInfo;

var captainTodaySearch;

require(['grid', 'topBar', 'layout', 'date'], function () {
    var postData;
    var _tmpCorpId="",_mftDiscCode="",_mftTypeCode="";
    $('#top').topBar({
        left: [{
            type: 'filter-more',
            dateType: 'custom',
            search: function () {
                search();
            },
            item: [
                {
                    text: '时间快捷',
                    name1: 'beginTime',
                    name2: 'endTime',
                    type: 'dateLine'
                }, {
                    text: 'ECU节点',
                    name: 'ecuMftCode',
                    type: 'item-select',
                    dict: 'ECU00000',
                    data: [
                        {text: '全部', value: ''}
                    ]
                }, {
                    text: '故障等级',
                    name: 'mftGradeCode',
                    type: 'item-select',
                    data: [
                        {text: '全部', value: ''},
                        {text: '严重', value: '1',selected:true},
                        {text: '警告', value: '3'},
                        {text: '一般', value: '2'},
                        {text: '正常', value: '4'}

                    ]
                }, {
                    text: '修复状态',
                    name: 'isHandle',
                    type: 'item-select',
                    data: [
                        {text: '全部', value: ''},
                        {text: '已修复', value: '0'},
                        {text: '未修复', value: '1',selected:true}
                    ]
                },
                {
                    text: '故障名称',
                    name: 'mftTypeName',
                    width: '140',
                    type: 'text'
                }
            ]
        }
        ],
        right: [
            {
                text: '导出',
                type: 'export-btn',
                authority: '',
                item: [
                    {
                        text: 'Excel导出',
                        click: function () {
                            exportFile('Excel');
                        }
                    },
                    {
                        text: 'PDF导出',
                        click: function () {
                            exportFile('Pdf');
                        }
                    }
                ]
            }, {
                text: '故障位置查询',
                type: 'btn',
                click: function () {
                    var ids = $('#grid').grid("getGridParam", "selarrrow");
                    if (ids && ids.length > 0) {
                        var data = new Array();  // 在这里构造车辆数据的数组
                        for (var i = 0; i < ids.length; i++) {
                            var obj = new Object();
                            var rowData = $("#grid").grid("getRowData", ids[i]);
                            obj.licPltNo = rowData.licPltNo;
                            obj.driverName = "";
                            obj.loLgt = rowData.beginLoLgt;
                            obj.loLtt = rowData.beginLoLtt;
                            obj.direction = rowData.beginLoDrc;
                            obj.type = rowData.ecuMftName;
                            obj.beginTime = rowData.mftOccurTime;
                            obj.endTime = rowData.mftRpaTime;
                            data.push(obj);
                        }
                        openLocationDetailInfoDialog("位置信息查询", data); //弹出的标题和数据
                    }
                    else {
                        $.messager.alert("警告", "没有数据。", "info");
                    }
                }
            },
            {
                text: '手动修复',
                type: 'btn',
                authority: '',
                click: function () {
                    var dateType = $("#top").parent().getValues().dateType;
                    if(dateType=='01'){
                        var selectRowIds = $('#grid').getGridParam().selarrrow;
                        var carIds = [];
                        var mftTypeCodes = [];
                        var mftDiscCodes = [];
                        $.each(selectRowIds, function (index, item) {
                            var row = $('#grid').getRowData(item);
                            var statusStr = row.status;
                            if (statusStr=='未修复') {
                                carIds.push(row.carId);
                                mftTypeCodes.push(row.mftTypeCode);
                                mftDiscCodes.push(row.mftDiscCode);
                            }
                        });
                        if (carIds.length == 0) {
                            $.messager.alert("提示", "请选择要修复的车辆记录", "info");
                            return;
                        }
                        $.messager.confirm("是否修复", "确定手工修复选择的车辆记录？", function (r) {
                            if (r) {
                                $.ajaxExt({
                                    url: "/realTimeFailure/manualRepirTodayFault.htm",
                                    data: {carIds: carIds.toString(),mftTypeCodes:mftTypeCodes.toString(),mftDiscCodes:mftDiscCodes.toString()}
                                }).done(function (data) {
                                    $('#grid').trigger("reloadGrid");
                                });
                            }
                        });
                    }
                    else{
                        var selectRowIds = $('#grid').getGridParam().selarrrow;
                        var rcrdIds = [];
                        $.each(selectRowIds, function (index, item) {
                            var row = $('#grid').getRowData(item);
                            var statusStr = row.status;
                            if (statusStr=='未修复') {
                                rcrdIds.push(row.rcrdId);
                            }
                        });
                        if (rcrdIds.length == 0) {
                            $.messager.alert("提示", "请选择要修复的车辆记录", "info");
                            return;
                        }
                        $.messager.confirm("是否修复", "确定手工修复选择的车辆记录？", function (r) {
                            if (r) {
                                $.ajaxExt({
                                    url: "/realTimeFailure/manualRepirFault.htm",
                                    data: {orgIds: rcrdIds.join(',')}
                                }).done(function (data) {
                                    $('#grid').trigger("reloadGrid");
                                });
                            }
                        });
                    }
                }
            }
        ]
    });

    $('body').layout();

    //跳转车辆画像-车辆故障页面
    goCarInfo = function (carId) {
        $.openTab('6bad880fef164ec6adaea7b18420eb6e', 'gotoSearch', [carId]);
    };
    
  //跳转到线路信息页面
    goLineInfo = function(lineId){
    	var data = {};
    	data.lineId = lineId;
    	$.openTab('4db17f8a322b4749a61eb2f8a12023ae','showLineInfo',[data]);
    }

    gotoSearchFaultDetails = function (data) { 
        passParams = data;
        if (data.lineIds) {
            //切换成线路
            commonFun.showLeftTree(commonFun.lineTree);
            //勾选并展开节点
            commonFun.setCheckedNodes(data.lineIds);
        }
        else if (data.carIds) {
            //切换成车辆
            commonFun.showLeftTree(commonFun.carTree);
            //勾选并展开节点
            commonFun.setCheckedNodes(data.carIds);
        }
        $('.topBar').find('[name=beginTime]').val(data.beginTime);
        $('.topBar').find('[name=endTime]').val(data.endTime);
        if(data.isHandle){
        	$("a[data-val='"+data.isHandle+"']",".more-area").click();
        }
        if(data.isHandle){
        	$("a[data-val='"+data.isHandle+"']",".more-area").click();
        }
        $('#grid').grid('setGridParam', {
            page: 1,
            datatype: "json",
            postData: passParams
        }).trigger("reloadGrid");
    }

    function exportFile(suffix) {
        if ($('#grid').getGridParam("reccount") > 0) {
            var url = "/realTimeFailure/exportRealTimeFail" + suffix + ".htm";
            if (passParams) {
                $.exportFile(url, passParams);
            } else {
                if (getPostData()) {
                    $.exportFile(url, postData);
                }
                else {
                    $.messager.alert("提示", "请选择查询车辆/机构/驾驶员。", "info");
                }
            }
        }
        else {
            $.messager.alert("提示", "请先查询数据。", "info");
        }
    }

    //获取左侧选择的节点信息
    function getPostData() {
        var rcx = commonFun.getTreeCheckNodeToArgs();
        if (rcx) {
            postData = $.extend(rcx, $("#top").parent().getValues());
        }
        return rcx;
    }

    function search() {
        passParams = null;
        if (getPostData()) {
        	postData.tmpCorpId = _tmpCorpId;
        	postData.mftDiscCode = _mftDiscCode;
        	postData.mftTypeCode = _mftTypeCode;
        	console.info(postData);
            $('#grid').grid('setGridParam', {
                page: 1,
                datatype: "json",
                postData: postData
            }).trigger("reloadGrid");
            _tmpCorpId="",_mftDiscCode="",_mftTypeCode="";
            postData.tmpCorpId = "";
        	postData.mftDiscCode = "";
        	postData.mftTypeCode = "";
        }
    }

    function openLocationDetailInfoDialog(title, data) {
        if (!locationDetailInfoDialog) {
            locationDetailInfoDialog = $('<div>').dialog({
                title: title,
                url: './common/map/mapLocation.htm',
                height: $(window.parent).height() * 0.8,
                width: $(window.parent).width() * 0.85
            });
        }
        locationDetailInfoDialog.dialog('open');
        locationDetailInfoDialog.dialog('exec', 'showMapLocation', data);
    }

    //查询故障详细位置
    queryLocation = function (id) {
        var data = new Array();
        var obj = new Object();
        var rowData = $("#grid").grid("getRowData", id);
        obj.licPltNo = rowData.licPltNo;
        obj.driverName = "";
        obj.loLgt = rowData.beginLoLgt;
        obj.loLtt = rowData.beginLoLtt;
        obj.direction = rowData.beginLoDrc;
        obj.type = rowData.ecuMftName;
        obj.beginTime = rowData.mftOccurTime;
        obj.endTime = rowData.mftRpaTime;
        data.push(obj);
        openLocationDetailInfoDialog("位置信息查询", data); //弹出的标题和数据
    }

    $('#grid').grid({
        url: "/realTimeFailure/searchRealTimeFaults.htm",
        colModel: [{name: "rcrdId", label: "rcrdId",hidden: true},
            {name: "carId", label: "carId",hidden: true},
            {name: "lineId", label: "lineId", hidden: true},
            {name: "beginLoLgt", label: "beginLoLgt", hidden: true},
            {name: "beginLoLtt", label: "beginLoLtt", hidden: true},
            {name: "beginLoDrc", label: "beginLoDrc", hidden: true},
            {name: "organName", label: "所属机构", width: 80},
            {name: "lineName", label: "运营线路", width: 80,formatter: 'customCurrency',formatoptions:{
                redbtn:true,
                css:'text-link c-blue',
                clickFn:function(rowObject,cellvalue){
                	goLineInfo(rowObject.lineId);
                }
            }},
            {name: "licPltNo", label: "车牌号", width: 80,formatter: function (cellvalue,options,rowObject) {
            	return "<b><a href='javascript:void(0);' onclick='goCarInfo(\"" + rowObject.carId + "\")' class='text-link c-blue'>" + cellvalue + "</a></b>";
            }},
            {name: "carInCd", label: "车辆编号", width: 80},
            {name: "ecuMftName", label: "ECU节点", width: 80},
            {name: "mftTypeCode", label: "mftTypeCode",hidden: true},
            {name: "mftDiscCode", label: "mftDiscCode",hidden: true},
            {name: "mftTypeName", label: "故障名称", width: 120},
            {name: "spdOfMotVhi", label: "车速(km/h)", align: "right", width: 120},
            {name: "rtteSpd", label: "转速(r/min)", align: "right", width: 120},
            {name: "mftOccurTime", label: "发生时间", width: 80},
            {name: "mftRpaTime", label: "最后上报时间", width: 120},
            {
                name: "locate", label: "发生站点", width: 80,
                formatter: function (cellvalue, options, rowObject) {
                    return "<b><a href='javascript:void(0);' onclick='queryLocation(\"" + options.rowId + "\")' style='color: blue;'>" + cellvalue + "</a></b>";
                }
            },
            {name: "status", label: "处理状态", width: 80},
            {name: "mftOccurFreq", label: "发生频率", align: "right", width: 80}],
        showPaper: true,
        gridComplete: function () {
            var rowIds = $('#grid').jqGrid('getDataIDs');
            var cssprop = "";
            var cssprop1 = "";
            for (var i = 0; i < rowIds.length; i++) {
                var rowId = rowIds[i];
                var rowObject = $('#grid').grid('getRowData', rowId);
                if (rowObject.status == '已修复') {
                    cssprop = {color: "#01B468"};
                } else if (rowObject.status == '未修复') {
                    cssprop = {color: "#FF100B"};
                } else if (rowObject.status == '已修复,但持续发生') {
                    cssprop = {color: "#EA7500"};
                }
                $('#grid').grid("setCell", rowId, "status", rowObject.status, cssprop);
                if (rowObject.mftOccurFreq > 5) {
                    cssprop1 = {color: "#FF100B"};
                } else {
                    cssprop1 = {color: "#000"};
                }
                $('#grid').grid("setCell", rowId, "mftOccurFreq", rowObject.mftOccurFreq, cssprop1);
            }
            var cells = $('#grid').find('td[aria-describedby="grid_locate"]');
            $.each(cells, function (i, obj) {
                var title = $('#grid').jqGrid('getCell', rowIds[i], 2) + "," + $('#grid').jqGrid('getCell', rowIds[i], 3);
                $(obj).attr('title', title);
            });
        }
    });


    itemSearch = function (data) {
        $("input[name='mftTypeName']").val("");
        //切换成线路
        commonFun.showLeftTree(commonFun.lineTree);
        //勾选并展开节点
        commonFun.setCheckedNodes(data.lineId);
        $("div[name='mftGradeCode']").find("a[data-val='']").click();
        $("a[data-val='01']").click();
    };
    
    captainSearch = function(data){
    	$("input[name='mftTypeName']").val("");
        //切换成线路
        commonFun.showLeftTree(commonFun.carTree);
        //勾选并展开节点
        commonFun.setCheckedNodes(data.carId);
        $("div[name='mftGradeCode']").find("a[data-val='1']").click();
        $("a[data-val='01']").click();
    };

    captainTodaySearch = function(data){
        $("input[name='mftTypeName']").val("");
        //切换成线路
        commonFun.showLeftTree(commonFun.lineTree);
        //勾选并展开节点
        commonFun.setCheckedNodes(data.lineIds);
        $("div[name='mftGradeCode']").find("a[data-val='']").click();
        $("div[name='isHandle']").find("a[data-val='']").click();
        $("a[data-val='01']").click();
    };

    realTimeFailWarn = function () {
        //默认未修复
        $("a[data-val='1']","[name='isHandle']").click();
        var today = (new Date()).format();
        var Ids = [];
        var node = commonFun.getNodesByType("CAR");
        if (node && node.length > 0) {
            $.each(node, function (index, item) {
                Ids.push(item.id);
            });
            $('#grid').grid('setGridParam', {
                page: 1,
                datatype: "json",
                postData: {
                	"mftGradeCode": "",
                    "driverIds": "",
                    "carIds": Ids,
                    "lineIds": "",
                    "type": "CAR",
                    "beginTime": today,
                    "endTime": today + " 23:59:59",
                    "isHandle":"1"
                }
            }).trigger("reloadGrid");
        }
    };

    
    
    searchFaultDetail = function (data) {
        commonFun.showLeftTree(commonFun.lineTree);
        commonFun.setCheckedNodes(data.lineId);
        $("div[name='mftGradeCode']").find("a[data-val='']").click();
        if(data.lineId == 'ALL'){
        	commonFun.checkAllNodes(true);
        	getPostData();
        	_tmpCorpId = data.corpId;
        	_mftDiscCode = data.mftDiscCode;
        	_mftTypeCode = data.mftTypeCode;
        }
        $("input[name='mftTypeName']").val(data.mftTypeName);
        $("a[data-val='" + data.dateType + "']").click();
    };
});